package priv.winnine.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.springframework.util.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Pattern;

@Slf4j
public class AuthUtil {

    private static final ThreadLocal<MessageDigest> SHA1_DIGEST = ThreadLocal.withInitial(() -> {
        try {
            return MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException e) {
            log.error("Create message digest instance error: ", e);
        }
        return null;
    });

    public static String generateSignature(String accountSid, String authToken, String timestamp) {
        String plainSignature = accountSid + authToken + timestamp;
        byte[] result = SHA1_DIGEST.get().digest(plainSignature.getBytes());
        return Hex.encodeHexString(result);
    }

    public static boolean match(String path, String pathPattern) {
        if (StringUtils.isEmpty(pathPattern)) {
            return false;
        }
        for (String s : pathPattern.split(",")) {
            if (Pattern.compile(s).matcher(path).matches()) return true;
        }
        return false;
    }
}
